<template>
    <a-alert message="错误日志" v-show="alertShow" show-icon banner type="error">
        <template #description>
            <div v-html="alertDescription">
            </div>
        </template>
        <template #action>
            <a-button size="small" type="text" @click="alertShow = false">关闭</a-button>
        </template>
    </a-alert>
    <DomainInfoSelectOptions v-model:data="selectData"></DomainInfoSelectOptions>

    <a-spin :style="spinStyle" :spinning="tableLoading">
        <a-space style="margin-top: 20px" align="start">
            <a-dropdown placement="bottom">
                <template #overlay>
                    <a-menu>
                        <a-menu-item @click="exportDataHandleVisible = true"> 导出数据</a-menu-item>
                        <a-menu-item @click="websiteInfoAnalysus"> 网站信息分析</a-menu-item>
                        <a-menu-item @click="generareTargetKeyword"> 网站分析(生成目标关键词)</a-menu-item>
                        <a-menu-item @click="updateWebsitePublishInfo">更新网站发布信息</a-menu-item>
                        <a-menu-item @click="bulkBindAd">批量绑定广告</a-menu-item>
                        <a-menu-item @click="bulkUpdateTpl">批量更新模版</a-menu-item>
                        <a-menu-item @click="bulkSetTplWyc">批量设置模版伪原创</a-menu-item>
                        <a-menu-item @click="bulkBindSecurityConfig">批量绑定安全配置</a-menu-item>
                        <a-menu-item @click="bulkBindDynamicAd">批量绑定动态广告</a-menu-item>
                        <a-menu-item @click="bulkBindDynamicLinkConfig">批量设置动态外链</a-menu-item>
                        <a-menu-item @click="bulkPushFriendLink">批量推送友链</a-menu-item>
                        <a-menu-item @click="websiteSeoReport">网站seo分析报告</a-menu-item>
                        <a-menu-item @click="visitTriggerHistory">网站访问触发历史数据</a-menu-item>
                        <a-menu-item @click="updateWebsiteVisitTriggerFields">更新网站最近1、2周访问触发字段</a-menu-item>
                        <a-sub-menu key="sub2" title="网站排名">
                            <a-menu-item @click="kwdRankAnalysis(1)"> 孕站群与城市分析 </a-menu-item>
                            <a-menu-item @click="kwdRankAnalysis(2)"> 孕站群与根词分析</a-menu-item>
                            <a-menu-item @click="websiteRankingAnalysis"> 网站排名分析报告</a-menu-item>
                            <a-menu-item @click="WebRankContinedUpOrDownAnalysisModelVisible = true">
                                排名持续下跌或上涨分析</a-menu-item>
                            <a-menu-item @click="rankingTypeAndRootAnalysus"> 排名词分类与根词分析</a-menu-item>
                        <a-menu-item @click="rankingAnalysisUpsAndDowns">排名分析（涨/跌）</a-menu-item>
                        <a-menu-item @click="singleWebRankingAnalysisUpsAndDowns">单站排名分析（涨/跌）</a-menu-item>
                       
                        </a-sub-menu>
                        <a-sub-menu key="sub1" title="运维">
                            <a-menu-item @click="syncYunyinWebsite" v-if="useAdminShow()">同步运营端网站列表</a-menu-item>
                            <a-menu-item @click="bulkUpdateNginxRule">批量修改Nginx规则</a-menu-item>
                            <a-menu-item @click="bulkUpdateWebProgram">批量修改网站程序类型</a-menu-item>
                            
                            <a-menu-item @click="updateDeDeWebsiteHtFile">更新DeDe Ht文件</a-menu-item>
                            <a-menu-item @click="updateDeDeWebsiteSysConfigFile">更新DeDe 系统配置缓存</a-menu-item>
                            <a-menu-item @click="updateDeDeWebsiteColumnCache">更新DeDe 栏目缓存</a-menu-item>
                        </a-sub-menu>
                    </a-menu>
                </template>
                <a-button type="primary">
                    工具
                    <DownOutlined />
                </a-button>
            </a-dropdown>
            <a-dropdown placement="bottom">
                <template #overlay>
                    <a-menu>
                        <a-menu-item @click="toWebsiteReferer"> 访问来源-曲线图</a-menu-item>
                        <a-menu-item @click="toWebsiteEvent"> 触发事件-曲线图</a-menu-item>
                        <a-menu-item @click="toWebsiteSpider"> 网站蜘蛛-曲线图</a-menu-item>
                        <a-menu-item @click="toWebsiteOtherSpider"> 网站其他蜘蛛-曲线图</a-menu-item>
                        <a-menu-item @click="toWebsiteBaiduSpider2"> 网站百度蜘蛛2-曲线图</a-menu-item>
                        <a-menu-item @click="toRankingChart"> 排名曲线图</a-menu-item>
                        <a-menu-item @click="toWebsiteArticles"> 网站文章列表</a-menu-item>
                        <a-menu-item @click="toArticleInnerChain">文章已发内链</a-menu-item>
                        <a-menu-item @click="toWebsiteKeywordDensity">网站关键词密度</a-menu-item>
                        <a-menu-item @click="toUsedAdWebsiteList">已使用广告网站列表</a-menu-item>
                        <a-menu-item @click="toBaiduPushControl">百度推送控制台</a-menu-item>
                        <a-menu-item @click="toHtmlWyc">HTML伪原创列表</a-menu-item>
                        <a-menu-item @click="toDashboard">仪表盘</a-menu-item>
                        <a-menu-item @click="toUsedWebSecurityConfigWebsiteList">已使用网站安全配置列表</a-menu-item>
                        <a-menu-item @click="toWebExternalLinkAnalysis">网站外链分析</a-menu-item>
                        <a-menu-item @click="toDynamicOutlink">动态外链网站列表</a-menu-item>
                        <a-menu-item @click="toDynamicAdWebsite">动态广告网站</a-menu-item>
                    </a-menu>
                </template>
                <a-button type="dashed">
                    跳转到
                    <DownOutlined />
                </a-button>
            </a-dropdown>

            <a-button @click="domainInfoShowFieldsModalVisible = true">选择显示字段</a-button>
            <a-select v-model:value="searchField" style="width: 150px">
                <a-select-option value="domain">域名搜索</a-select-option>
                <a-select-option value="new_root_domain">根域名(新)</a-select-option>
                <a-select-option value="id">ID搜索</a-select-option>
                <a-select-option value="cdn_server_name">CDN服务器名称</a-select-option>
                <a-select-option value="origin_server_name">源服务器名称</a-select-option>
                <a-select-option value="cdn_ip">CDN主IP</a-select-option>
                <a-select-option value="nip">内网IP</a-select-option>
                <a-select-option value="public_ip">公网IP</a-select-option>
                <a-select-option value="m_template_name">m模版</a-select-option>
                <a-select-option value="web_template_name">pc模版</a-select-option>
                <a-select-option value="nginx__name">nginx规则</a-select-option>
            </a-select>
            <a-textarea placeholder="请输入搜索的值" style="width: 300px" v-model:value="searchValue"> </a-textarea>
            <a-button type="primary" @click="searchFunc">
                <template #icon>
                    <SearchOutlined />
                </template>
                搜索
            </a-button>
            <a-button type="link" @click="otherConditionComponentVisible = true">其他条件</a-button>
        </a-space>
        <a-divider style="margin: 15px 0"></a-divider>
        <a-table v-if="total" sticky :columns="columns" :data-source="tableData" @change="handleTableChange" bordered
            :pagination="false" :row-class-name="(_record, index) => (index % 2 === 1 ? 'table-striped' : undefined)"
            size="small" class="table" :row-selection="rowSelection" :scroll="{ x: tableScrollX }"
            :rowKey="(row: any) => row.id"></a-table>
        <a-row justify="center" v-if="total > 10" style="margin-top: 10px">
            <a-pagination v-model:current="params.page" v-model:pageSize="params.size" show-quick-jumper showSizeChanger
                :total="total" :page-size-options="pageSizeOptions" @change="pageChange"
                :show-total="(total: number) => `总计 ${total} 项`" />
        </a-row>
    </a-spin>
    <KeywordRankingAnalysisComponent :selectedRowKeys="selectedRowKeys" v-model:visible="kwdRankVModalVisible"
        :type="kwdRankType" />
    <RankingAnalysisUpsAndDownsComponent :es-ids="webids" :es-query="esQuery"
        v-model:visible="rankingAnalysisUpsAndDownsVisible" />
        
        <SingleWebRankingAnalysisUpsAndDownsComponent :ids="webids" 
        v-model:visible="singleWebRankingAnalysisUpsAndDownsVisible" />
    <WebsiteRankingAnalysisComponent :es-ids="webids" :es-query="esQuery"
        v-model:visible="websiteRankingAnalysisModelVisible" />
    <WebRankContinedUpOrDownAnalysisComponent :es-ids="webids" :es-query="esQuery"
        v-model:visible="WebRankContinedUpOrDownAnalysisModelVisible" />
    <KeywordRankingAndKeytypeAndRootKwdAnalysisComponent :selectedRowKeys="selectedRowKeys"
        v-model:visible="kwdRankAndKeyTypeAndRootKwdVisible" />
    <WebsiteInfoAndCityAndRootKeywordAnalysisComponent :selectedRowKeys="selectedRowKeys"
        v-model:visible="websiteInfoAnalysusVisible" />
    <WebsiteInfoAnalysisGetTargetKeywordComponent :selectedRowKeys="selectedRowKeys"
        v-model:visible="generareTargetKeywordAnalysusVisible" />
    <DomainInfoShowFieldsModal v-model:visible="domainInfoShowFieldsModalVisible" v-model:showFields="showFields"
        :fieldOptionsGroupObj="fieldOptionsGroupObj"></DomainInfoShowFieldsModal>
    <ExportDataHandleComponent :fields="showFields" v-model:visible="exportDataHandleVisible"
        :fieldOptions="fieldOptions" :es-ids="webids" :es-query="esQuery" />
    <OtherConditionComponent v-model:visible="otherConditionComponentVisible" v-model:conditions="otherCondition" />
    <WebsiteBulkBindAdvertiserComponent :es-ids="webids" v-model:visible="websiteBulkBindAdvertiserVisible" />
    <BulkBindSecurityConfigComponent :es-ids="webids" v-model:visible="bulkBindSecurityConfigVisible" />
    <BulkBindDynamicLinkConfigComponent :es-ids="webids" :rows="selectedRow"
        v-model:visible="bulkBindDynamicLinkVisible" />
    <WebsiteBulkUpdateTplComponent :es-ids="webids" :program_id="fristProgramType"
        v-model:visible="websiteBulkUpdateTplVisible" />
    <WebsiteBulkSetTplWycComponent :es-ids="webids" v-model:visible="websitebulkSetTplWycVisible" />
    <WebsiteBulkUpdateNginxRuleComponent :rows="selectedRow" v-model:visible="bulkUpdateNginxRuleVisible" />
    <WebsiteBulkUpdateWebsiteProgramComponent :rows="selectedRow" v-model:visible="bulkUpdateWebProgramVisible" />
    <WebsiteDynamicAdComponent v-model:visible="bulkBindDynamicAdVisible" :rows="selectedRow"></WebsiteDynamicAdComponent>

    <WebsiteShowDataComponent :current-row="currentRow" v-model:visible="websiteShowDataVisible">
    </WebsiteShowDataComponent>
</template>

<script lang="ts" setup>
import { DomainInfoSelectOptions } from "@/components/home/tsx/commonComponents";
import { SearchOutlined, DownOutlined } from "@ant-design/icons-vue";
import { getWebsitesApi } from "@/api/main";
import {
    KeywordRankingAnalysisComponent,
    KeywordRankingAndKeytypeAndRootKwdAnalysisComponent,
    WebsiteInfoAndCityAndRootKeywordAnalysisComponent,
    WebsiteInfoAnalysisGetTargetKeywordComponent,
    DomainInfoShowFieldsModal,
    ExportDataHandleComponent,
    OtherConditionComponent,
    RankingAnalysisUpsAndDownsComponent,
    SingleWebRankingAnalysisUpsAndDownsComponent,
    WebsiteRankingAnalysisComponent,
    WebRankContinedUpOrDownAnalysisComponent,
    WebsiteBulkBindAdvertiserComponent,
    BulkBindSecurityConfigComponent,
    BulkBindDynamicLinkConfigComponent,
    WebsiteBulkUpdateTplComponent,
    WebsiteBulkSetTplWycComponent,
    WebsiteShowDataComponent,
    WebsiteBulkUpdateNginxRuleComponent,
    WebsiteBulkUpdateWebsiteProgramComponent,
    WebsiteDynamicAdComponent
} from "@/components/home/tsx/websitesComponents";
import { useAdminShow, useSpinLoadingState } from "@/hooks/useCommon";
import { useColumns, useSelectFields } from "@/hooks/main/useWebsites";
import { toUrl } from "@/utils/common";
import { updateWebsiteArticlePublishInfoApi } from "@/api/esArticle";
import {websiteSeoReportApi,visitTriggerHistoryApi} from "@/api/analysisAndReport"
import {updateDeDeHtFileApi,updateDeDeSysConfigFileApi,updateDeDeWebsiteColumnCacheApi} from "@/api/yunwei"
import { message } from "ant-design-vue";
import { syncWebsiteVisitAndTriggerFieldsApi, syncYunyinWebsiteApi } from "@/api/scripts";
import { pushWebsiteLinkApi } from "@/api/friendlyChain";
import { chunk } from "@/utils/lodash";
const { showFields, fieldOptions, fieldOptionsGroupObj } = useSelectFields();
const tableScrollX = computed(() => showFields.value.length * 200);
const esHostValue = ref("http://192.168.1.92:9200");
const esIndexValue = ref("");
const { spinStyle, viewLoading: tableLoading } = useSpinLoadingState();
const pageSizeOptions = ref<string[]>(["10", "20", "50", "100", "500", "1000", "1500"]);
const { columns, websiteShowDataVisible, currentRow } = useColumns(showFields);
// alert 是否展示
const alertShow = ref(false);
const alertDescription = ref("");
provide('alertShow', alertShow)
provide('alertDescription', alertDescription)
// 搜索字段 默认域名搜索
const searchField = ref("domain");
// 输入框的值
const searchValue = ref("");
// 域名显示字段 对话框 控制
const domainInfoShowFieldsModalVisible = ref(false);
// 字段筛选
const selectData = reactive<DomainInfoSelectFields>({
    web_user: -1,
    link_user: -1,
    content_user: -1,
    website_type: -1,
    program_type: -1,
    adapt_type: -1,
    ad_website: -1,
    jsc_type: -1,
    j_type: -1,
    domain_account: -1,
    dns_account: -1,
    guoneiad_type: -1,
    shipei_type: -1,
    ad_type: -1,
    keywords_type: -1,
    content_type: -1,
    website_group_type: [],
    neilian_type: -1,
    seo_type: -1,
    es_type: -1,
    benan: -1,
    multiple_choice_field1: [],
    multiple_choice_field2: [],
    multiple_choice_field3: [],
});
const fristProgramType = computed<number>(() => {
    if (!webids.value.length) {
        return 0
    }
    return tableData.value.find(item => item.id === webids.value[0])?.program_type
})

const tableData = ref<Array<Record<string, any>>>([]);
const total = ref(0);
const params: GetWebsites = reactive({ size: 10, page: 1 });
// 对话框数据
const kwdRankVModalVisible = ref(false);
const kwdRankType = ref(1);
const kwdRankAndKeyTypeAndRootKwdVisible = ref(false);
const websiteInfoAnalysusVisible = ref(false);
// 生成目标关键词
const generareTargetKeywordAnalysusVisible = ref(false);
// 当前页变化
const pageChange = (pageNumber: number) => {
    params.page = pageNumber;
    searchFunc();
};
const sortObj = {
    order: "",
    sort_field: ""
};
// 表格排序发生改变
const handleTableChange = (pag: any, filters: any, sorter: any) => {
    if (sorter.order) {
        sortObj.order = sorter.order.slice(0, sorter.order.length - 3);
        sortObj.sort_field = sorter.field;
    } else {
        sortObj.order = "";
    }
    searchFunc();
};
const esQuery = ref<Record<string, string>>({});
// 导出的页面展示
const exportDataHandleVisible = ref(false);
// 其他条件的页面展示
const otherConditionComponentVisible = ref(false);
// 其他条件
const otherCondition: Array<{
    field: string;
    value: string;
    type: number;
}> = reactive([]);

const searchFunc = () => {
    tableLoading.value = true;
    const targetKeywordIndexs = [];
    if (esIndexValue.value && esHostValue.value) {
        targetKeywordIndexs.push(`${esHostValue.value}@${esIndexValue.value}`);
    }
    getWebsitesApi({
        field: searchField.value,
        value: searchValue.value
            .split("\n")
            .map((s) => s.trim())
            .filter(Boolean)
            .join(","),
        ...params,
        ...selectData,
        ...sortObj,
        otherConditions: JSON.stringify(otherCondition),
        targetKeywordIndexs: targetKeywordIndexs.join(",")
    })
        .then((res) => {
            if (res.data.code === 200) {
                tableData.value = res.data.data;
                total.value = res.data.total;
                esQuery.value = res.data.query;
                // @ts-ignore
                if (total.value <= (params.page - 1) * params.size) {
                    params.page = 1;
                }
            }
        })
        .finally(() => (tableLoading.value = false));
};

// 收集行key
const selectedRowKeys = ref<Array<Record<string, number>>>([]);
const selectedRow = ref<Array<Record<string, any>>>([])
// 网站ID列表
const webids = ref<Array<number>>([]);
const rowSelection = ref<any>({
    checkStrictly: false,
    onSelect: (_: boolean, __: boolean, rows: DomainArtInfo[]) => {
        selectedRowKeys.value = rows.map((item) => ({ [item["pc_domain"]]: item.id }));
        selectedRow.value = rows
    },
    onSelectAll: (_: boolean, __: boolean, rows: DomainArtInfo[]) => {
        selectedRowKeys.value = rows.map((item) => ({ [item["pc_domain"]]: item.id }));
        selectedRow.value = rows
    },
    onChange: (rows: number[]) => {
        webids.value = rows
    }
});
// 分析
const kwdRankAnalysis = (type: 1 | 2) => {
    if (!selectedRowKeys.value.length) {
        return message.error("最少选择一项!");
    }
    kwdRankType.value = type;
    kwdRankVModalVisible.value = true;
};
// 网站排名持续下跌或上涨分析 modelVisit
const WebRankContinedUpOrDownAnalysisModelVisible = ref(false)
const websiteRankingAnalysisModelVisible = ref(false)
const websiteRankingAnalysis = () => {
    websiteRankingAnalysisModelVisible.value = true
}
// 自定义网站排名词与关键词分类,根词分析
const rankingTypeAndRootAnalysus = () => {
    if (!selectedRowKeys.value.length) {
        return message.error("最少选择一项!");
    }
    kwdRankAndKeyTypeAndRootKwdVisible.value = true;
};
const websiteInfoAnalysus = () => {
    if (!selectedRowKeys.value.length) {
        return message.error("最少选择一项!");
    }
    websiteInfoAnalysusVisible.value = true;
};
const generareTargetKeyword = () => {
    if (!selectedRowKeys.value.length) {
        return message.error("最少选择一项!");
    }
    selectedRowKeys.value.length = 1;
    generareTargetKeywordAnalysusVisible.value = true;
};
const updateWebsitePublishInfo = () => {
    const ids = selectedRowKeys.value.map((item) => Object.values(item)[0])
    updateWebsiteArticlePublishInfoApi({ ids, query: esQuery.value! }).then(res => {
        message.success("正在更新!!!")
    }).catch(e => {
        message.error("更新失败!")
    })
}
// 获取当前选择的id和查询条件
const getIdsAndQuery = () => {
    const ids = JSON.stringify(webids.value)
    const query = JSON.stringify(esQuery.value);
    return { ids, query };
};
const common = (routePath: string) => {
    const { ids } = getIdsAndQuery();
    const body = JSON.stringify({ query: esQuery.value });
    window.open(toUrl(`/statistics/${routePath}?ids=${ids}&body=${body}`));
};
// 跳转
const toWebsiteReferer = () => common("website-referer");
const toWebsiteEvent = () => common("website-event");
const toWebsiteSpider = () => common("website-spider");
const toWebsiteOtherSpider = () => common("website-other-spider");
const toWebsiteBaiduSpider2 = () => common("website-baidu-spider2");
const toWebsiteArticles = () => {
    const { ids, query } = getIdsAndQuery();
    window.open(toUrl(`/article-admin/articles?ids=${ids}&query=${query}`));
};
const toWebsiteKeywordDensity = () => {
    const { ids, query } = getIdsAndQuery();
    window.open(toUrl(`/esarticle/keyword-density?ids=${ids}&query=${query}`));
};
const toUsedAdWebsiteList = () => {
    window.open(toUrl(`/advertising-system/bind-list?query=${JSON.stringify(getEsQuery())}`));
}
const getEsQuery = () => {
    const { ids, query } = getIdsAndQuery();
    let esQuery: any = {}
    const ids2 = JSON.parse(ids)
    if (ids2.length) {
        esQuery["terms"] = {
            "id": ids2
        }
    } else {
        esQuery = JSON.parse(query)
    }
    return esQuery
}
const toUsedWebSecurityConfigWebsiteList = () => {
    window.open(toUrl(`/utils/web-security/already-bind-webs?query=${JSON.stringify(getEsQuery())}`));
}
const toWebExternalLinkAnalysis = () => {
    window.open(toUrl(`/analysis-and-report/external-link-analysis?query=${JSON.stringify(getEsQuery())}`));
}
const toDynamicOutlink = ()=>{
    window.open(toUrl(`/utils/dynamic-links/dynamic-websites?query=${JSON.stringify(getEsQuery())}`));
}
const toDynamicAdWebsite= ()=>{
    window.open(toUrl(`/utils/dynamic-ad?query=${JSON.stringify(getEsQuery())}`));
}
// 跳转到文章内链页面去
const toArticleInnerChain = () => {
    const { ids } = getIdsAndQuery();
    window.open(toUrl(`/article-admin/inner-chain-list?ids=${ids}`), "_blank");
};
const toRankingChart = () => {
    const { ids, query } = getIdsAndQuery();
    window.open(toUrl(`http://192.168.1.113:5100/#/curvediagram/mywebsite?arr=${ids}&query=${query}`));
};
const toBaiduPushControl = () => {
    const { ids } = getIdsAndQuery();
    window.open(toUrl(`/utils/baidu-push?ids=${ids}`));
}
const toDashboard = () => {
    let query = esQuery.value as Record<string, any>
    if (webids.value.length) {
        query = {
            "terms": {
                "id": webids.value
            }
        }
    }
    window.open(toUrl(`/analysis-and-report/dashboard?query=${JSON.stringify(query)}`));
}
const websiteSeoReport = ()=>{
    let query = esQuery.value as Record<string, any>
    if (webids.value.length) {
        query = {
            "terms": {
                "id": webids.value
            }
        }
    }
    websiteSeoReportApi(query).then(res=>{
        message.success("准备下载")
        window.open(import.meta.env.VITE_QZ_API_URL +  res.data.csv_file_path)
    }).catch(e=>{
        message.error("获取seo报告失败!")
    })
}
const visitTriggerHistory = ()=>{
    let query = esQuery.value as Record<string, any>
    if (webids.value.length) {
        query = {
            "terms": {
                "id": webids.value
            }
        }
    }
    visitTriggerHistoryApi(query).then(res=>{
        message.success("准备下载")
        window.open(import.meta.env.VITE_QZ_API_URL +  res.data.csv_file_path)
    }).catch(e=>{
        message.error("获取seo报告失败!")
    })
}

const updateWebsiteVisitTriggerFields = ()=>{
    syncWebsiteVisitAndTriggerFieldsApi().then(res=>{
        message.success("操作成功!")
    }).catch(e=>{
        message.error("操作失败!")
    })
}
const toHtmlWyc = () => {
    const { ids } = getIdsAndQuery();
    window.open(toUrl(`/utils/html-wyc?ids=${ids}`));
}
const rankingAnalysisUpsAndDownsVisible = ref(false)
// 关键词排名分析 涨跌
const rankingAnalysisUpsAndDowns = () => {
    rankingAnalysisUpsAndDownsVisible.value = true
}
const singleWebRankingAnalysisUpsAndDownsVisible = ref(false)
const singleWebRankingAnalysisUpsAndDowns = () => {
    if(webids.value.length != 1){
        return message.error("只能选择单个网站!")
    }
    singleWebRankingAnalysisUpsAndDownsVisible.value = true
}
const websiteBulkBindAdvertiserVisible = ref(false)
// 添加绑定广告
const bulkBindAd = () => {
    if (webids.value.length === 0) {
        return message.error("最少选择一项!")
    }
    websiteBulkBindAdvertiserVisible.value = true
}
const bulkBindSecurityConfigVisible = ref(false)
const bulkBindSecurityConfig = () => {
    if (webids.value.length === 0) {
        return message.error("最少选择一项!")
    }
    bulkBindSecurityConfigVisible.value = true
}
const bulkBindDynamicAdVisible = ref(false)
const bulkBindDynamicAd = ()=>{
    if (webids.value.length === 0) {
        return message.error("最少选择一项!")
    }
    const programTypes = Array.from(new Set(selectedRow.value.map(item=>item.program_type)))
    if(programTypes.length > 1){
        return message.error("请选择相同的程序类型!") 
    }
    const allowProgramTypes = [1,26]
    if(!allowProgramTypes.includes(programTypes[0])){
        return message.error("只支持 dede,百斗v2 程序类型!")
    }
    bulkBindDynamicAdVisible.value = true   
}
const bulkBindDynamicLinkVisible = ref(false)
const bulkBindDynamicLinkConfig = () => {
    if (webids.value.length === 0) {
        return message.error("最少选择一项!")
    }
    const programTypes = Array.from(new Set(selectedRow.value.map(item=>item.program_type)))
    if(programTypes.length > 1){
        return message.error("请选择相同的程序类型!") 
    }
    const allowProgramTypes = [1,11,17,18,23,26]
    if(!allowProgramTypes.includes(programTypes[0])){
        return message.error("只支持 dede,百斗v2,泛站 程序类型!")
    }
    bulkBindDynamicLinkVisible.value = true
}
// 批量推送友链
const bulkPushFriendLink = () => {
    if (!selectedRow.value.length) {
        return message.error("最少选择一项!");
    }
    if (selectedRow.value.length > 20) {
        return message.error("最多选择20项!");
    }
    selectedRow.value.map(item => {
        // 推送友链
        pushWebsiteLinkApi(item.pc_domain)
            .then(() => {
                message.success(`[${item.pc_domain}]` + "操作成功!");
            })
            .catch((e) => {
                message.error(`[${item.pc_domain}]` + e.response.data.msg);
            });
    })
};
const updateDeDeWebsiteHtFile = ()=>{
    const selectedRows = webids.value.map(id=>{
        return tableData.value.find(item=>item.id === id)
    }).filter(Boolean)
    const rows = selectedRows.filter(item=>item.program_type === 1)
    if(rows.length === 0){
        return message.error("最少选择一项")
    }
    
    chunk(rows as Array<Record<string, any>>,15).map(async (items,index)=>{
        await new Promise((resolve)=>{
            setTimeout(()=>{
                resolve(true)
            },3000 * index)
        }).then(()=>{
            Promise.allSettled(items.map(item=>{
                // @ts-ignore
                return updateDeDeHtFileApi(item['pc_domain'],item['nip']).then(res=>{
                    message.success(`[${item.pc_domain}]操作成功!`,2)
                }).catch(e=>{
                    message.error(`[${item.pc_domain}]操作失败!`,2)
                })
            })).then(res=>{
                message.success(`第${index + 1}批次更新完成!`)
            })
        })
    })
}
const updateDeDeWebsiteSysConfigFile = ()=>{
    const selectedRows = webids.value.map(id=>{
        return tableData.value.find(item=>item.id === id)
    }).filter(Boolean)
    const rows = selectedRows.filter(item=>item.program_type === 1)
    if(rows.length === 0){
        return message.error("最少选择一项")
    }
    chunk(rows as Array<Record<string, any>>,15).map(async (items,index)=>{
        await new Promise((resolve)=>{
            setTimeout(()=>{
                resolve(true)
            },3000 * index)
        }).then(()=>{
            Promise.allSettled(items.map(item=>{
                // @ts-ignore
                return updateDeDeSysConfigFileApi(item['pc_domain'],item['nip']).then(res=>{
                    message.success(`[${item.pc_domain}]操作成功!`,2)
                }).catch(e=>{
                    message.error(`[${item.pc_domain}]操作失败!`,2)
                })
            })).then(res=>{
                message.success(`第${index + 1}批次更新完成!`)
            })
        })
    })
}
    
const updateDeDeWebsiteColumnCache = ()=>{
    const selectedRows = webids.value.map(id=>{
        return tableData.value.find(item=>item.id === id)
    }).filter(Boolean)
    const rows = selectedRows.filter(item=>item.program_type === 1)
    let ids = [] as Array<number>
    let pc_domain_ip_map:Record<string,any> = {}
    if(rows.length !== 0){
        ids = rows.map(item=>item.id)
        // @ts-ignore
        pc_domain_ip_map = rows.reduce((p,c)=>{
            p[c['pc_domain']] = c['nip']
            return p
        },{})
    }
    updateDeDeWebsiteColumnCacheApi(ids,pc_domain_ip_map).then(res=>{
        message.success("操作成功!")
    }).catch(e=>{
        message.error("操作失败!")
    })
}
const websiteBulkUpdateTplVisible = ref(false)
const bulkUpdateTpl = () => {
    if (webids.value.length === 0) {
        return message.error("最少选择一项!")
    }
    websiteBulkUpdateTplVisible.value = true
}
const websitebulkSetTplWycVisible = ref(false)
const bulkSetTplWyc = () => {
    if (webids.value.length === 0) {
        return message.error("最少选择一项!")
    }
    websitebulkSetTplWycVisible.value = true
}
const bulkUpdateNginxRuleVisible = ref(false)
const bulkUpdateNginxRule = () => {
    if (selectedRow.value.length === 0) {
        return message.error("最少选择一项!")
    }
    bulkUpdateNginxRuleVisible.value = true
}
const bulkUpdateWebProgramVisible = ref(false)
const bulkUpdateWebProgram = () => {
    if (selectedRow.value.length === 0) {
        return message.error("最少选择一项!")
    }
    bulkUpdateWebProgramVisible.value = true
}
// 同步运营端网站列表
const syncYunyinWebsite = () => {
    message.success("开始同步!!!")
    syncYunyinWebsiteApi().then(res => {
    })
}
const skeletonLoading = ref(true);
const $route = useRoute()
onMounted(() => {
    if ($route.query.value) {
        searchValue.value = ($route.query.value as string).replaceAll(",", "\n")
    }
    searchFunc();
    setTimeout(() => {
        skeletonLoading.value = false;
    }, 200);
});
</script>
